<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic|LiSu:300,300italic,400,400italic,700,700italic|youyuan:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css">
  <link rel="stylesheet" href="/blog/lib/pace/pace-theme-bounce.min.css">
  <script src="/blog/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"zchao666.gitee.io","root":"/blog/","scheme":"Gemini","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="什么是反射？JAVA反射机制是在&#x3D;&#x3D;运行状态中&#x3D;&#x3D;，对于任意一个类，都能够知道这个类的所有属性和方法；对于任意一个对象，都能够调用它的任意一个方法和属性；这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。 反射的作用在运行时，通过反射可以判断任意一个对象所属的类、构造任意一个类的对象、判断任意一个类所具有的成员变量和方法、调用任意一个对象的方法以及给任意一个类的属性设值等等">
<meta property="og:type" content="article">
<meta property="og:title" content="Java反射机制">
<meta property="og:url" content="https://zchao666.gitee.io/blog/2020/03/13/Java%E7%9A%84%E5%8F%8D%E5%B0%84%E6%9C%BA%E5%88%B6/index.html">
<meta property="og:site_name" content="小郭的博客">
<meta property="og:description" content="什么是反射？JAVA反射机制是在&#x3D;&#x3D;运行状态中&#x3D;&#x3D;，对于任意一个类，都能够知道这个类的所有属性和方法；对于任意一个对象，都能够调用它的任意一个方法和属性；这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。 反射的作用在运行时，通过反射可以判断任意一个对象所属的类、构造任意一个类的对象、判断任意一个类所具有的成员变量和方法、调用任意一个对象的方法以及给任意一个类的属性设值等等">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://img-blog.csdnimg.cn/2020031318021815.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMTkzMTMz,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200313211343231.png">
<meta property="article:published_time" content="2020-03-13T14:49:44.000Z">
<meta property="article:modified_time" content="2020-03-13T14:50:41.857Z">
<meta property="article:author" content="小郭">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="反射">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/2020031318021815.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMTkzMTMz,size_16,color_FFFFFF,t_70">

<link rel="canonical" href="https://zchao666.gitee.io/blog/2020/03/13/Java%E7%9A%84%E5%8F%8D%E5%B0%84%E6%9C%BA%E5%88%B6/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true
  };
</script>

  <title>Java反射机制 | 小郭的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

  
  
		<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
		<script>
		/* 社会主体核心价值观效果 */
		var a_idx = 0;
		jQuery(document).ready(function ($) {
		  $("body").click(function (e) {
			var a = new Array("富强", "民主", "文明", "和谐", "自由", "平等", "公正", "法治", "爱国", "敬业", "诚信", "友善");
			var $i = $("<span/>").text(a[a_idx]);
			a_idx = (a_idx + 1) % a.length;
			var x = e.pageX,
			  y = e.pageY;
			$i.css({
			  "z-index": 100000000,
			  "top": y - 20,
			  "left": x,
			  "position": "absolute",
			  "font-family": "LiSu",
			  "font-weight": "bold",
			  "color": "#ff6651"
			});
			$("body").append($i);
			$i.animate({
			  "top": y - 180,
			  "opacity": 0
			}, 1500, function () {
			  $i.remove();
			});
		  });
		});
	</script>
  

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">小郭的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
        <li class="menu-item menu-item-留言">

    <a href="/blog/comments/" rel="section"><i class="fa fa-fw fa-commenting"></i>留言</a>

  </li>
        <li class="menu-item menu-item-commonweal">

    <a href="/blog/404/" rel="section"><i class="fa fa-fw fa-heartbeat"></i>公益 404</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/GZC986707252" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://zchao666.gitee.io/blog/2020/03/13/Java%E7%9A%84%E5%8F%8D%E5%B0%84%E6%9C%BA%E5%88%B6/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/uploads/avatar.jpg">
      <meta itemprop="name" content="小郭">
      <meta itemprop="description" content="一个还在不断学习的编程小白！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="小郭的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java反射机制
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-03-13 22:49:44 / 修改时间：22:50:41" itemprop="dateCreated datePublished" datetime="2020-03-13T22:49:44+08:00">2020-03-13</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/blog/2020/03/13/Java%E7%9A%84%E5%8F%8D%E5%B0%84%E6%9C%BA%E5%88%B6/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/blog/2020/03/13/Java%E7%9A%84%E5%8F%8D%E5%B0%84%E6%9C%BA%E5%88%B6/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h3 id="什么是反射？"><a href="#什么是反射？" class="headerlink" title="什么是反射？"></a>什么是反射？</h3><p>JAVA反射机制是在==运行状态中==，对于任意一个类，都能够知道这个类的所有属性和方法；对于任意一个对象，都能够调用它的任意一个方法和属性；这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。</p>
<h3 id="反射的作用"><a href="#反射的作用" class="headerlink" title="反射的作用"></a>反射的作用</h3><p>在运行时，通过反射可以判断任意一个对象所属的类、构造任意一个类的对象、判断任意一个类所具有的成员变量和方法、调用任意一个对象的方法以及给任意一个类的属性设值等等。</p>
<a id="more"></a>
<h3 id="Class类"><a href="#Class类" class="headerlink" title="Class类"></a>Class类</h3><p>在Java中，除了<code>int</code>等基本数据类型以外，其他的类型全部都是<code>class</code>（包括<code>interface</code>）。<br><code>class</code>是由JVM在运行状态中动态加载的，JVM第一次读取到<code>class</code>类型时，就将它加入到内存。每加载一种<code>class</code>，JVM就为它创建一个<code>Class</code>类型的实例，并关联起来。</p>
<p>例如<code>String</code>类型，JVM加载<code>String</code>类型时，先读取<code>String.class</code>字节码文件到内存，并创建一个与<code>String</code>类关联的<code>Class</code>实例。</p>
<p>通过查看源码可以知道，<code>Class</code>类型的构造方法是用了<code>private</code>修饰，因此，只有JVM才能够创建实例，自己的程序是无法创建的。</p>
<p>由于JVM为每个加载的<code>class</code>创建了对应的<code>Class</code>实例，并在实例中保存了该<code>class</code>的所有信息，包括类名、包名、父类、实现的接口、所有方法、字段等，因此，如果获取了某个<code>Class</code>实例，我们就可以通过这个<code>Class</code>实例获取到该实例对应的<code>class</code>的所有信息。</p>
<h4 id="获取Class实例的三种方法"><a href="#获取Class实例的三种方法" class="headerlink" title="获取Class实例的三种方法"></a>获取<code>Class</code>实例的三种方法</h4><ul>
<li><strong>通过一个类的静态变量<code>class</code>获取：</strong><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Class cls = String<span class="class">.<span class="keyword">class</span></span>;</span><br></pre></td></tr></table></figure></li>
<li><strong>通过实例变量提供的getClass()方法获取：</strong><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">String s = <span class="string">"Hello"</span>;</span><br><span class="line">Class cls = s.getClass();</span><br></pre></td></tr></table></figure></li>
<li><strong>知道完整类名，通过静态方法Class.forName()获取</strong><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Class cls = Class.forName(<span class="string">"java.lang.String"</span>);</span><br></pre></td></tr></table></figure>

</li>
</ul>
<p>当获取到Class实例，就可以通过该实例获取对应类型的实例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取String的Class实例</span></span><br><span class="line">Class cls = String<span class="class">.<span class="keyword">class</span></span>;</span><br><span class="line"><span class="comment">// 创建一个String实例</span></span><br><span class="line"><span class="comment">//相当于 new String()</span></span><br><span class="line">String s = (String) cls.newInstance();</span><br></pre></td></tr></table></figure>
<p>注意：通过<code>Class.newInstance()</code>可以创建类实例，它的局限是：只能调用<code>public</code>的无参数构造方法。带参数的构造方法，或者非public的构造方法都无法通过<code>Class.newInstance()</code>被调用。</p>
<h4 id="动态加载"><a href="#动态加载" class="headerlink" title="动态加载"></a>动态加载</h4><p>JVM在执行Java程序的时候，并不是一次性把所有用到的<code>class</code>全部加载到内存，而是第一次需要用到<code>class</code>时才加载。利用JVM动态加载<code>class</code>的特性，我们可以在运行期间根据条件加载不同的实现类。</p>
<h3 id="访问字段"><a href="#访问字段" class="headerlink" title="访问字段"></a>访问字段</h3><p><code>Class</code>类提供以下几个方法来获取相应的字段：</p>
<ul>
<li><code>Field getField(name)</code>：根据字段名获取某个public的field（包括父类）</li>
<li><code>Field getDeclaredField(name)</code>：根据字段名获取当前类的某个field（不包括父类）</li>
<li><code>Field[] getFields()</code>：获取所有public的field（包括父类）</li>
<li><code>Field[] getDeclaredFields()</code>：获取当前类的所有field（不包括父类）</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> edu.gzc;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Main</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> NoSuchFieldException </span>&#123;</span><br><span class="line">	<span class="comment">// write your code here</span></span><br><span class="line">        Class stdClass = Student<span class="class">.<span class="keyword">class</span></span>;</span><br><span class="line">        <span class="comment">// 获取public字段"score":</span></span><br><span class="line">        System.out.println(stdClass.getField(<span class="string">"score"</span>));</span><br><span class="line">        <span class="comment">// 获取继承的public字段"name":</span></span><br><span class="line">        System.out.println(stdClass.getField(<span class="string">"name"</span>));</span><br><span class="line">        <span class="comment">// 获取private字段"grade":</span></span><br><span class="line">        System.out.println(stdClass.getDeclaredField(<span class="string">"grade"</span>));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Student</span> <span class="keyword">extends</span> <span class="title">Persion</span></span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">int</span> score;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> grade;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Persion</span></span>&#123;</span><br><span class="line">    <span class="keyword">public</span> String name;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>输出：<br><img src="https://img-blog.csdnimg.cn/2020031318021815.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQxMTkzMTMz,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>一个<code>Field</code>对象包含了一个字段的所有信息：</p>
<ul>
<li><code>getName()</code>：返回字段名称，例如，”name”；</li>
<li><code>getType()</code>：返回字段类型，也是一个Class实例，例如，String.class；</li>
<li><code>getModifiers()</code>：返回字段的修饰符，它是一个int，不同的bit表示不同的含义。</li>
</ul>
<p><strong>通过<code>Field</code>对象获取字段信息</strong> </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">Field score = stdClass.getDeclaredField(<span class="string">"score"</span>);</span><br><span class="line">System.out.println(score.getName());  <span class="comment">//输出 score</span></span><br><span class="line">System.out.println(score.getType());  <span class="comment">///输出 int</span></span><br><span class="line"><span class="comment">//获取字段修饰符</span></span><br><span class="line"><span class="keyword">int</span> m =score.getModifiers();</span><br><span class="line">System.out.println(Modifier.isPublic(m));   <span class="comment">// 输出 true</span></span><br></pre></td></tr></table></figure>

<p><strong>获取字段值和设置字段值</strong><br>先获取<code>Class</code>实例，再获取<code>Field</code>实例：</p>
<ul>
<li>用<code>Field.get(Object)</code>获取指定实例的指定字段的值。</li>
<li>用<code>Field.set(Object, Object)</code>实现设置字段值，其中第一个<code>Object</code>参数是指定的实例，第二个<code>Object</code>参数是待修改的值。<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Main</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">// write your code here</span></span><br><span class="line">        <span class="comment">//获取字段值</span></span><br><span class="line">        Persion p = <span class="keyword">new</span> Persion(<span class="string">"xiaoming"</span>);</span><br><span class="line">        Class c = p.getClass();</span><br><span class="line">        Field f = c.getDeclaredField(<span class="string">"name"</span>);</span><br><span class="line">        <span class="comment">//不管字段是public，还是private，都允许访问</span></span><br><span class="line">        f.setAccessible(<span class="keyword">true</span>);</span><br><span class="line">        Object value = f.get(p);</span><br><span class="line">        System.out.println(value);   <span class="comment">// 输出 xiaoming </span></span><br><span class="line">		<span class="comment">//设置字段值</span></span><br><span class="line">        f.set(p, <span class="string">"zhangsan"</span>);</span><br><span class="line">        System.out.println(p.getName());   <span class="comment">//输出  zhangsan</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Persion</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> String name;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Persion</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
如果获取非<code>public</code>字段，会抛出<code>IllegalAccessException</code>异常，可以将<code>private</code>修改为<code>public</code> ，或者在得到<code>Field</code>对象后，设置访问权限：<code>f.setAccessible(true);</code>。</li>
</ul>
<p><strong>但该方法也可能会失败，如果JVM运行期存在<code>SecurityManager</code>，那么它会根据规则进行检查，有可能阻止<code>setAccessible(true)</code>。</strong></p>
<h3 id="调用方法"><a href="#调用方法" class="headerlink" title="调用方法"></a>调用方法</h3><p>通过<code>Class</code>实例获取所有<code>Method</code>信息。<code>Class</code>类提供了以下几个方法来获取<code>Method</code>：</p>
<ul>
<li><code>Method getMethod(name, Class...)</code>：获取某个<code>public</code>的<code>Method</code>（包括父类） </li>
<li><code>Method  getDeclaredMethod(name, Class...)</code>：获取当前类的某个Method（不包括父类） </li>
<li><code>Method[]  getMethods()</code>：获取所有public的Method（包括父类）</li>
<li><code>Method[]  getDeclaredMethods()</code>：获取当前类的所有Method（不包括父类）</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> edu.gzc;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Main</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">	 	Class stuClass=Student<span class="class">.<span class="keyword">class</span></span>;</span><br><span class="line">        <span class="comment">//获取public 方法setScore，参数为int</span></span><br><span class="line">        System.out.println(stuClass.getDeclaredMethod(<span class="string">"setScore"</span>, <span class="keyword">int</span><span class="class">.<span class="keyword">class</span>))</span>;;</span><br><span class="line">        <span class="comment">//获取继承的public方法getName,无参数</span></span><br><span class="line">        System.out.println(stuClass.getMethod(<span class="string">"getName"</span>));</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Student</span> <span class="keyword">extends</span> <span class="title">Persion</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> score;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> grade;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getScore</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> score;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setScore</span><span class="params">(<span class="keyword">int</span> score)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.score = score;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Persion</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> String name;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setName</span><span class="params">(String name)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> name;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>输出：<br><img src="https://img-blog.csdnimg.cn/20200313211343231.png" alt="在这里插入图片描述"><br><strong>一个<code>Method</code>对象包含一个方法的所有信息：</strong></p>
<ul>
<li><code>getName()</code>：返回方法名称，例如：”<code>getScore</code>“；</li>
<li><code>getReturnType()</code>：返回方法返回值类型，也是一个<code>Class</code>实例，例如：String.class；</li>
<li><code>getParameterTypes()</code>：返回方法的参数类型，是一个<code>Class</code>数组，例如：<code>{String.class, int.class}</code>；</li>
<li><code>getModifiers()</code>：返回方法的修饰符，它是一个<code>int</code>，不同的bit表示不同的含义。</li>
</ul>
<p><strong>调用方法</strong><br>对<code>Method</code>实例调用<code>invoke</code>就相当于调用该方法，<code>invoke</code>的第一个参数是对象实例，即在哪个实例上调用该方法，后面的可变参数要与方法参数一致，否则将报错。<br>方法：<code>Object invoke(Object instance, Object... parameters)</code></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.lang.reflect.Method;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        String str = <span class="string">"hello world"</span>;</span><br><span class="line">        <span class="comment">// 获取String substring(int)方法，参数为int:</span></span><br><span class="line">        Method m =String.class.getDeclaredMethod("substring", int.class);</span><br><span class="line">        <span class="comment">// 在str对象上调用该方法并获取结果:</span></span><br><span class="line">        String result= (String) m.invoke(str, <span class="number">6</span>);</span><br><span class="line">        <span class="comment">// 打印调用结果:</span></span><br><span class="line">        System.out.println(result);   <span class="comment">//输出 world</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>调用静态方法</strong><br>如果获取到的<code>Method</code>表示一个静态方法，调用静态方法时，由于无需指定实例对象，所以<code>invoke</code>方法传入的第一个参数永远为<code>null</code>。<br>例如 ：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Integer n = (Integer) m.invoke(<span class="keyword">null</span>, <span class="string">"12345"</span>);</span><br></pre></td></tr></table></figure>
<p><strong>调用非public方法</strong><br>通过设置<code>setAccessible(true)</code>来访问非<code>public</code>方法。<code>setAccessible(true)</code>可能会失败。</p>
<p><strong>注意</strong>：使用反射调用方法时，仍然遵循多态原则。</p>
<h3 id="调用构造方法"><a href="#调用构造方法" class="headerlink" title="调用构造方法"></a>调用构造方法</h3><p>使用反射来创建实例，则需要调用 <code>Class</code>提供的<code>newInstance()</code>方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Person p = Person<span class="class">.<span class="keyword">class</span>.<span class="title">newInstance</span>()</span>;</span><br></pre></td></tr></table></figure>

<p><strong>要注意的是，<code>newInstance()</code>只能调用该类无参的public的无参构造方法。</strong></p>
<p>那么如何调用任意构造方法呢？？？</p>
<p>为了调用任意的构造方法，Java的反射API提供了<code>Constructor</code>对象，它包含一个构造方法的所有信息，可以创建一个实例。</p>
<p><strong>通过Class实例获取<code>Constructor</code>的方法如下：</strong></p>
<ul>
<li><code>getConstructor(Class...)</code>：获取某个<code>public</code>的<code>Constructor</code>；</li>
<li><code>getDeclaredConstructor(Class...)</code>：获取某个<code>Constructor</code>；</li>
<li><code>getConstructors()</code>：获取所有<code>public</code>的<code>Constructor</code>；</li>
<li><code>getDeclaredConstructors()</code>：获取所有<code>Constructor</code>。</li>
</ul>
<p>调用非public的Constructor时，必须首先通过setAccessible(true)设置允许访问。setAccessible(true)可能会失败。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.lang.reflect.Constructor;</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">Test</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">//获取构造方法Integer(int)</span></span><br><span class="line">        Constructor cons1 = Integer<span class="class">.<span class="keyword">class</span>.<span class="title">getConstructor</span>(<span class="title">int</span>.<span class="title">class</span>)</span>;</span><br><span class="line">        <span class="comment">//调用构造方法</span></span><br><span class="line">        Integer n1 = (Integer) cons1.newInstance(<span class="number">123</span>);</span><br><span class="line">        System.out.println(n1);  <span class="comment">// 输出 123</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// 获取构造方法Integer(String)</span></span><br><span class="line">        Constructor cons2 = Integer<span class="class">.<span class="keyword">class</span>.<span class="title">getConstructor</span>(<span class="title">String</span>.<span class="title">class</span>)</span>;</span><br><span class="line">        Integer n2 = (Integer) cons2.newInstance(<span class="string">"456"</span>);</span><br><span class="line">        System.out.println(n2);  <span class="comment">//  输出 456</span></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<h3 id="获取继承关系"><a href="#获取继承关系" class="headerlink" title="获取继承关系"></a>获取继承关系</h3><p><strong>获取父类的Class：</strong><br>通过<code>Class</code>提供的<code>Class  getSuperclass()</code>方法可以获取父类的<code>Class</code>。</p>
<p><strong>获取interface：</strong></p>
<ul>
<li>通过<code>Class</code>提供的<code>Class[]  getInterfaces()</code>方法可以获取该类实现的接口的<code>Class</code>。</li>
<li><code>getInterfaces()</code>只返回当前类直接实现的接口类型，并不包括其父类实现的接口类型。</li>
<li>对所有<code>interface</code>的<code>Class</code>调用<code>getSuperclass()</code>返回的是<code>null</code>，获取接口的父接口要用<code>getInterfaces()</code>。</li>
<li>如果一个类没有实现任何<code>interface</code>，那么<code>getInterfaces()</code>返回空数组。</li>
<li>两个<code>Class</code>实例，要判断一个向上转型是否成立，可以调用<code>isAssignableFrom()</code>。</li>
</ul>

    </div>

    
    
    
        <div class="reward-container">
  <div></div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/blog/uploads/wechatpay.jpg" alt="小郭 微信支付">
        <p>微信支付</p>
      </div>

  </div>
</div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/blog/tags/Java/" rel="tag"><i class="fa fa-tag"></i> Java</a>
              <a href="/blog/tags/%E5%8F%8D%E5%B0%84/" rel="tag"><i class="fa fa-tag"></i> 反射</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2020/03/12/Git%E7%9B%B8%E5%85%B3%E6%93%8D%E4%BD%9C%E5%91%BD%E4%BB%A4/" rel="prev" title="Git相关操作命令">
      <i class="fa fa-chevron-left"></i> Git相关操作命令
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2020/03/15/SpringMVC%E4%B8%AD%E7%9A%84%E6%8B%A6%E6%88%AA%E5%99%A8/" rel="next" title="SpringMVC中的拦截器">
      SpringMVC中的拦截器 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#什么是反射？"><span class="nav-text">什么是反射？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#反射的作用"><span class="nav-text">反射的作用</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Class类"><span class="nav-text">Class类</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#获取Class实例的三种方法"><span class="nav-text">获取Class实例的三种方法</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#动态加载"><span class="nav-text">动态加载</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#访问字段"><span class="nav-text">访问字段</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#调用方法"><span class="nav-text">调用方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#调用构造方法"><span class="nav-text">调用构造方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#获取继承关系"><span class="nav-text">获取继承关系</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="小郭"
      src="/blog/uploads/avatar.jpg">
  <p class="site-author-name" itemprop="name">小郭</p>
  <div class="site-description" itemprop="description">一个还在不断学习的编程小白！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">26</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">44</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/GZC986707252" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;GZC986707252" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/u/3278894871" title="微博 → https:&#x2F;&#x2F;weibo.com&#x2F;u&#x2F;3278894871" rel="noopener" target="_blank"><i class="fa fa-fw fa-weibo"></i>微博</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://blog.csdn.net/qq_41193133" title="CSDN → https:&#x2F;&#x2F;blog.csdn.net&#x2F;qq_41193133" rel="noopener" target="_blank"><i class="fa fa-fw fa-globe"></i>CSDN</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:986707252@qq.com" title="E-Mail → mailto:986707252@qq.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">小郭</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v4.2.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> v7.7.2
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>


  <script defer src="/blog/lib/three/three.min.js"></script>
    <script defer src="/blog/lib/three/canvas_lines.min.js"></script>


  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>




  
<script src="/blog/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = '昵称,邮箱,链接';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : true,
      appId      : 'dQIv9pCVNauk7ezmEU35I8sW-gzGzoHsz',
      appKey     : '2BGfzddNSeijXJJtTofkbuJx',
      placeholder: "走过路过，千万不要错过，一起聊聊吧！",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>